package ds.tree;

public class ChildrenSum {

	private boolean isNodeSumOfChildren= true;
	
	private static class TreeNode{
		int value;
		TreeNode left = null;
		TreeNode right = null;
		
		TreeNode(int val){
			this.value = val;
		}
		
		public String toString(){
			return String.valueOf(value);
		}
	}

	public void sumOfChildren(TreeNode node){
		if(node == null || (node.left == null && node.right == null))
			return;
		if(isNodeSumOfChildren){
			if(node.value == (((node.left != null )?node.left.value:0) + ((node.right != null ) ?node.right.value:0))){
				sumOfChildren(node.left);
				sumOfChildren(node.right);
			}	else	{
				isNodeSumOfChildren = false;
			}
		}
	}
	private static TreeNode wrongTree(){
		TreeNode A = new TreeNode(1);
		TreeNode B = new TreeNode(2);
		TreeNode C = new TreeNode(3);
		TreeNode D = new TreeNode(4);
		TreeNode E = new TreeNode(5);
		TreeNode F = new TreeNode(6);
		TreeNode G = new TreeNode(7);	
		TreeNode H = new TreeNode(8);
		TreeNode I = new TreeNode(9);
		
		A.left = B;
		A.right = C;
		B.left = D;
		B.right = E;
		C.left = F;
		C.right = G;
		G.left = H;
		G.right = I;
		return A;
	}
	private static TreeNode correctTree(){

		TreeNode A = new TreeNode(100);
		TreeNode B = new TreeNode(50);
		TreeNode C = new TreeNode(50);
		TreeNode D = new TreeNode(25);
		TreeNode E = new TreeNode(25);
		TreeNode F = new TreeNode(50);
		TreeNode G = new TreeNode(40);	

		A.left = B;
		A.right = C;
		B.left = D;
		B.right = E;
		C.left = F;
//		C.right = G;		
		
		return A;
	}
	public static void main(String[] args) {
		ChildrenSum sum = new ChildrenSum();
		sum.sumOfChildren(wrongTree());
		System.out.println(sum.isNodeSumOfChildren);
		sum.isNodeSumOfChildren = true;
		sum.sumOfChildren(correctTree());
		System.out.println(sum.isNodeSumOfChildren);
	}

}
